package com.taxi.comm.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

import org.apache.commons.lang.StringUtils;

public class ZipUtils {

	public static String LwsZipInnerFileName = "json.txt";

	public static byte[] Zip(byte[] bContent) throws IOException {
		ZipOutputStream zos = null;
		ByteArrayOutputStream baos = null;
		try {
			baos = new ByteArrayOutputStream();
			zos = new ZipOutputStream(baos);
//			zos.setMethod(ZipOutputStream.DEFLATED);
			ZipEntry ze = new ZipEntry(LwsZipInnerFileName);
			ze.setSize(bContent.length);
			zos.putNextEntry(ze);
			zos.write(bContent, 0, bContent.length);
			zos.closeEntry();
			zos.flush();
		} finally {
			if (zos != null) {
				zos.close();
			}
		}
		
		if (baos != null) {
			return baos.toByteArray();
		} else {
			return null;
		}
	}

	public static byte[] UnZip(byte[] bZipContent) throws Exception {
		ZipInputStream zis = null;
		try {
			ByteArrayInputStream bais = new ByteArrayInputStream(bZipContent);
			zis = new ZipInputStream(bais);
			while (true) {
				ZipEntry ze = zis.getNextEntry();
				if (ze == null) {
					throw new Exception("Cannot found the expected file in package (json.txt)");
				}
				if (!ze.isDirectory()
						&& StringUtils
								.equals(LwsZipInnerFileName, ze.getName())) {
					
					
					// unzip
//					int zeSize= (int) ze.getSize();
//					byte[] buffer = new byte[zeSize];
//					zis.read(buffer, 0, buffer.length);
//					return buffer;
					ByteArrayOutputStream bOut = new ByteArrayOutputStream();
					for (int c = zis.read(); c != -1; c = zis.read()) {
				        bOut.write(c);
				      }
					
					return bOut.toByteArray();
				}
			}
		} finally {
			if (zis != null) {
				zis.close();
			}
		}
	}

}
